package org.goldenport.g3.app

import org.goldenport.g3._
import org.goldenport.g3.atom._
import org.goldenport.g3.messages._
import org.goldenport.g3.messages.datastore._
import org.goldenport.g3.messages.query._

/**
 * @since   Sep. 25, 2010
 * @version Oct.  8, 2010
 * @author  ASAMI, Tomoharu
 */
class AtomDb extends G3Application with UseRecord {
  val kind = 'feed
  val schema = Schema(AutoIdField,
                      'twitterid,
                      'title,
                      ('date, XDate),
                      ('content, XString))
//    println("AtomDb = " + schema.fields.map(_.constraints))
//  val url = "http://gihyo.jp/feed/atom"
  val url = "http://twitter.com/statuses/public_timeline.atom"

  datastore('db)
  service('feed, url)

  html('viewtop, "Atom to Database") {
<body>
<h1>Atom to Database</h1>

<ul>
  <li><a href="/init">Initialize Database</a></li>
  <li><a href="/list">List Feeds</a></li>
  <li><a href="/update">Collect Feeds</a></li>
</ul>

</body>
  }

  channel('viewinitrun) invoke("init") agent {
    case _ => Html("Initialize Result", 
<body>
<h1>Initialize Result</h1>

Success!

<ul>
  <li><a href="/">Return Menu</a></li>
</ul>

</body>
    )
  }

  channel('viewlist) invoke("list") agent {
    case rs: RecordSet => Html("Feed List",
<body>
<h1>Feed List</h1>

<g.list/>

<ul>
  <li><a href="/">Return Menu</a></li>
</ul>

</body>
    ) schema schema += rs
  }

  channel('viewupdaterun) invoke("update") agent {
    case _ => Html("Collect done",
<body>
<h1>Entry</h1>

Atom feeds are updated.

<ul>
  <li><a href="/">Return Menu</a></li>
</ul>

</body>
    ) schema schema
  }

  agents('init)(MsgSeq(Drop(kind), Create(kind, schema))) invoke("db")

  agents('list)(Query(RecordQuery(AllFieldSlot(kind)))) invoke("db")

  channel('update) invoke("feed") agent {
    case AtomFeed(feed) => {
      Post(kind,
           feed.toRecordSet(entry => {
             Record('twitterid -> entry.id,
                    'title -> entry.title,
                    'date -> entry.updated,
                    'content -> entry.contentText)
           }))
    }
  } invoke("db")

  port("/") invoke("viewtop")
  port("/init") invoke("viewinitrun")
  port("/list") invoke("viewlist")
  port("/update") invoke("viewupdaterun")
  port("/service/init") invoke("init")
  port("/service/list") invoke("list")
  port("/service/update") invoke("update")
}
